#!coding:utf-8
'''
Created on Aug 16, 2012

@author: join
'''
from lottery_jx.common import tools, utils
from lottery_jx.models import SystemSettings, Account
import datetime

@tools.render
def systemsettings(request):
    '''显示系统设置页面'''
    
    return 'settings/systemsettings.html'

@tools.ajaxrender
def settingsDataList(request):
    '''获取所有系统设置的数据'''
    page = int(request.POST.get('page', 1))
    rows = int(request.POST.get('rows', 20))
    
    params={'deleted':0}
    
    count = SystemSettings.objects.filter(**params).count()
    datas = SystemSettings.objects.filter(**params)[(page-1)*rows: page*rows]
    
    try:
        if datas:
            data_list = []
            for data in datas:
                
                
                data_list.append({'desc': data.desc,
                                  'itemvalue': data.itemvalue,
                                  'itemvalue_new': data.itemvalue2,
                                  'legaldate': utils.convert_datetime_to_str(data.legaldate,'%Y-%m-%d %H:%M:%S'),
                                  'updatetime': utils.convert_datetime_to_str(data.updated_at,'%Y-%m-%d %H:%M:%S'),
                                  'action':data.id})
            values = {'total':count,
                      'rows': data_list,
                      }
            return values
        else:
            return None
    except Exception as e:
        print str(e)
        return None   

@tools.render
def showSettingsEdit(request,settingsId):
    '''显示修改系统设置页面'''
    if not settingsId:
        return u'系统错误',500
    
    setting = SystemSettings.objects.get(id=settingsId)
    
    if setting.legaldate:
        if setting.itemvalue2 and setting.legaldate<datetime.datetime.now():
            setting.itemvalue = setting.itemvalue2
    return 'settings/_settings_modify.html',{'setting':setting}

@tools.ajaxrender
def submitEdit(request):
    '''提交系统设置修改内容'''
    try:
        itemid = request.POST.get('id')
        value = request.POST.get('itemvalue')
        valid_time = request.POST.get('valid_time')
        desc = request.POST.get('desc')
        
        if not valid_time:
            return u'生效时间不能为空',400
        valid_time = valid_time + " 00:00:00"
        if not itemid or not value:
            return u'设置项的值不能为空',500
        print valid_time
        if utils.format_datetime(valid_time)<datetime.datetime.now():
            return u'生效时间应晚于当前时间',400
        
        settings = SystemSettings.objects.get(pk=int(itemid))
        if not settings.legaldate:
            settings.itemvalue2 = value
        elif settings.legaldate<datetime.datetime.now(): #之前修改过的配置已经生效，需要转存到itemvalue字段
            settings.itemvalue = settings.itemvalue2
        settings.itemvalue2 = value #修改的内容存入itemvalue2字段
   
        
        settings.legaldate = utils.format_datetime(valid_time)
        if settings.itemname == 'alarm_shop':
            settings.desc="店主阀值"
        elif settings.itemname == 'alarm_tianfu':
            settings.desc="公司阀值"
        else:
            settings.desc="银联费率"

        settings.save()
        
        return u'修改设置成功',200
    except Exception as e:
        print str(e)
        return u'修改失败。错误原因：%s' % str(e),500
    
@tools.render
def modifypwd(request):
    '''密码修改页面'''
    at=request.session['user'].accountType
    return 'settings/modifypwd.html',{'accountType':at}

@tools.ajaxrender
def submit_modify(request):
    '''提交密码修改'''
    try:
        account = request.session['user']
        oldpwd = request.POST.get('oldpwd')
        newpwd = request.POST.get('newpwd')
        repeatpwd = request.POST.get('repeatpwd')
        
        account = Account.objects.get(pk=account.id)
        if account.password != tools.getMD5Str(oldpwd):
            return u'旧密码错误，请重新输入。',400
        
       
        if newpwd != repeatpwd:
            return u'新密码两次输入不一致'
        
        account.password = tools.getMD5Str(newpwd)
        account.save()
        if request.session.has_key('user'):
            del request.session['user']
            del request.session['lastlogintime']
    except Exception as e:
        return u'系统错误，错误原因：%s' % str(e),500
